package com.yy.device.boot.handler;

import cn.hutool.core.util.HexUtil;
import com.yy.device.boot.protocol.IMessage;
import com.yy.device.boot.protocol.RegisterMessage;
import com.yy.device.boot.protocol.ReportMessage;
import com.yy.device.boot.protocol.TaskMessage;
import com.yy.device.boot.protocol.TaskQueryMessage;
import com.yy.device.constant.DeviceConstant;
import com.yy.device.enums.DeviceHeadEnum;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 协议解码器
 *
 * @author sunzhiqiang
 * @date 2022/01/19 14:48:52
 */
@Slf4j
public class ProtoDecoder extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        ByteBuf copy = byteBuf.copy();
        byte[] bytes = new byte[copy.readableBytes()];
        copy.writeBytes(copy);
        log.info(HexUtil.encodeHexStr(bytes));

        int header = byteBuf.readByte() & 0xff;
        byte version = byteBuf.readByte();
        short lenght = byteBuf.readShortLE();
        DeviceHeadEnum headEnum = DeviceHeadEnum.getEnumByType(header);
        switch (headEnum) {
            case REGISTER_TASK:
                IMessage registerMessage = new RegisterMessage();
                registerMessage.decode(byteBuf);
                out.add(registerMessage);
                break;
            case REPORT:
                if (lenght == DeviceConstant.REPORT_LENGTH) {
                    IMessage reportMessage = new ReportMessage();
                    reportMessage.decode(byteBuf);
                    out.add(reportMessage);
                } else if (lenght == DeviceConstant.TASK_LENGTH) {
                    IMessage taskMessage = new TaskMessage();
                    taskMessage.decode(byteBuf);
                    out.add(taskMessage);
                } else if (lenght == DeviceConstant.QUERY_TASK_LENGTH) {
                    IMessage taskMessage = new TaskQueryMessage();
                    taskMessage.decode(byteBuf);
                    out.add(taskMessage);
                }
                break;
            case HEART:
            default:
                break;
        }


    }
}
